<template>
  <div class="container tree-list-layout">
    <treeLocation @click="handleTreeClick" ref="treeLocation" class="box-left" />
    <!-- 仓库列表 -->
    <data-view
      class="box-right"
      ref="dataView"
      propViewKey="base_location"
      propViewForm="base/location/detail.vue"
      :propInitData="selectedTreeNode"
      @after-save="handleAfterSave"
      @after-delete="handleAfterDelete"
      @extra-button-click="handleExtraButtonClick"
      :propIsTdesign="true"
      @before-button-click="beforeButtonClick"
      @close="$refs.treeLocation.load()"
    />
    <!--绑定解绑库位耗材弹框 -->
    <customDrawer
      title="绑定解绑库位耗材"
      ref="bindDrawer"
      @confirm="bindOrUnbind('form', false, 'bindDrawer')"
      :widthPx="460"
      :heightPx="291"
      @cancel="handleDrawerCancel"
    >
      <template #content>
        <customForm :data="form" ref="form" :rules="rules">
          <template #content>
            <customFormItem label="库位编码" name="scanLocationCode" :parent="_self" :form="form" />
            <customFormItem label="SN/RFID" name="scanUniqueCode" :parent="_self" :form="form" />
          </template>
        </customForm>
      </template>
    </customDrawer>
    <!-- 库位耗材范围 -->
    <customDrawer title="库位耗材范围" ref="setMatrDrawer" :footer="false" @cancel="handleDrawerCancel">
      <template #content>
        <customForm :data="form" ref="setMatrForm" :rules="rules" style="margin: 16px 0">
          <template #content>
            <strong style="line-height: 32px"
              >库位：{{ locationInitData.name }}，代码：{{ locationInitData.code }}</strong
            >
            <customFormItem label="SN/RFID" name="scanUniqueCode2" :parent="_self" :form="form" />
            <t-button @click="bindOrUnbind('setMatrForm', true, 'setMatrDrawer')">绑定/解绑</t-button>
          </template>
        </customForm>
        <data-view
          @select-change="selectChange"
          @view-ready="viewReady"
          ref="dvLimitMatr"
          propViewKey="location_limit_matr"
          :propInitData="locationInitData"
          :propPreQueryWrapper="$newWrapper().eq('locationId', locationInitData.id)"
          :propIsTdesign="true"
        />
      </template>
    </customDrawer>
  </div>
</template>

<script>
import MatrSelect from '@/components/base/MatrSelect'
import treeLocation from '@/components/custom/bus/treeLocation.vue'

export default {
  name: 'location',
  data() {
    return {
      treeData: [],
      treeFilter: '',
      selectedTreeNode: null,
      treeEntry: '/base/location/all',
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      dialogSafeStockVisible: false,
      selectedRow: null,
      dialogLocationMatrVisible: false,
      locationInitData: {},
      matrDialogVisible: false,
      //每种类型数据加载标识，只加载一次
      ajaxLoadFlags: [false],

      //数据缓存
      ajaxLoadData: [null],
      form: {
        scanLocationCode: '',
        scanUniqueCode: '',
        scanUniqueCode2: '',
      },
      rules: {
        scanLocationCode: [{ required: true, message: '请输入库位编码', trigger: 'blur' }],
        scanUniqueCode: [{ required: true, message: '请输入SN/RFID', trigger: 'blur' }],
        scanUniqueCode2: [{ required: true, message: '请输入SN/RFID', trigger: 'blur' }],
      },
    }
  },
  watch: {
    treeFilter(val) {
      this.$refs.tree.filter(val)
    },
  },
  methods: {

    handleTreeClick(data) {
      this.selectedTreeNode = data
      let wrapper = this.$newWrapper().eq('parent_id', data.id).or('id', data.id) //包含自己
      this.$refs.dataView.setQueryWrapper(wrapper)
    },
    handleTreeFilter(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleAfterSave(status, data) {},
    handleAfterDelete() {},
    handleExtraButtonClick({ button, data }) {
      console.log('data', data)
      if (button.key == 'settingSafeStock') {
        this.dialogSafeStockVisible = true
        this.selectedRow = data
        this.$nextTick(() => {
          this.$refs.safeStockDv.setQueryWrapper(this.$newWrapper().eq('locationId', this.selectedRow.id))
        })
      } else if (button.key === 'setMatrScope') {
        //设置库位耗材范围
        this.$refs.setMatrDrawer.show()
        // this.dialogLocationMatrVisible = true
        this.locationInitData = data
        this.$nextTick(() => {
          let wrapper = this.$newWrapper().eq('locationId', this.locationInitData.id)
          this.$refs.dvLimitMatr.setQueryWrapper(wrapper)
        })
      } else if (button.key === 'up') {
        //上架
        this.$confirm('是否将该仓库的所有库存进行上架?<br>按照耗材单位匹配库位耗材关系', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning',
        })
          .then(() => {
            this.$ajax.get(`/wm/stock/upShelvesBatch?warehouseId=${data.warehouseId}`).then((response) => {
              if (response.code == 0) {
                this.utilMessage.success(response.msg)
              }
              this.utilVue.loadHide()
            })
          })
          .catch(() => {})
      } else if (button.key === 'bind') {
        this.$refs.bindDrawer.show()
      }
    },
    handleSelect(items) {
      if (items.length == 0 || !this.selectedRow) {
        return
      }
      let params = {
        locationId: this.selectedRow.id,
        matrIdList: items.map((matr) => matr.id),
      }
      this.$ajax.post('/base/safe_stock/settingSafeStock', params).then((resp) => {
        this.utilMessage.success(resp.msg)
        this.$refs.safeStockDv.fetchData()
      })
    },
    //单元格改变
    async selectChange({ row, column }) {
      let selectRow = column.selectRow
      console.log('this.locationInitData', this.locationInitData)
      if (column.property == 'packageUnit') {
        row.packageUnit = selectRow.packageUnit
        row.unitId = selectRow.id
      } else if (column.property == 'matrName') {
        row.locationId = this.locationInitData.id
        row.locationName = this.locationInitData.name
        row.locationIdcode = this.locationInitData.idcode
        row.locationCode = this.locationInitData.code
        row.warehouseId = this.locationInitData.warehouseId
        row.warehouseName = this.locationInitData.warehouseName
        row.locationType = this.locationInitData.type
        row.matrId = selectRow.id
        row.matrName = selectRow.name
        row.matrSpec = selectRow.spec
      }
    },
    //查询每一列对应grid数据源
    async getGridData({ row, column }) {
      let url = '/base/matr/list'
      let ajaxLoadIndex = 0
      let wrapper = this.$newWrapper()
      let editColumns = [
        { title: '耗材名称', field: 'name', width: 200, search: true },
        { title: '品规', field: 'spec', search: true },
      ]

      //设置编辑列
      await this.$refs.dvLimitMatr.setEditColumns('matrName', editColumns)

      //如果已经加载过了，则只设置数据源
      if (this.ajaxLoadFlags[ajaxLoadIndex]) {
        this.$refs.dvLimitMatr.setEditDatas('title', this.ajaxLoadData[ajaxLoadIndex])
        return
      }
      this.$refs.dvLimitMatr.setEditQueries('matrName', { wrapper })
      this.ajaxLoadFlags[ajaxLoadIndex] = true
    },

    viewReady() {
      let wrapper = this.$newWrapper()

      //wrapper条件
      this.$refs.dvLimitMatr.setEditQueries('matrName', wrapper)

      //固定数据筛选参数
      let userParam = {
        viewKey: 'matr_select_inorder',
        checkType: 'radio',
        useMsg: '数据筛选条件：正常耗材，同一耗材单位只允许添加到同一库位一次',
        //下一个编辑单元格
        nextFieldEditName: 'packageUnit',
        //筛选耗材的sql语句
        sqlFilterMatr:
          " and matr.id  in ( select matr_id from base_matr_unit where id not in ( select unit_id from location_limit_matr  where location_id ='" +
          this.locationInitData.id +
          "' ) )  ",
      }
      this.$refs.dvLimitMatr.setEditUserParam('matrName', userParam)
      this.syncMatrUnit()
    },
    //耗材单位初始化
    syncMatrUnit() {
      //wrapper条件
      let wrapper = this.$newWrapper()
      this.$refs.dvLimitMatr.setEditQueries('packageUnit', wrapper)

      //固定数据筛选参数
      let userParam = {
        viewKey: 'select_matr_unit_purchase',
        checkType: 'radio',
        useMsg: '数据筛选条件：所选耗材的单位',

        //前一个编辑单元格字段名
        beforeFieldEditName: 'matrName',
        //前一个单元格编辑值为空的提示
        beforeNullMsg: '请先选择耗材',
        //查询单位时的条件字段
        beforeFieldQueryName: 'matrId',
        //筛选耗材的sql语句
        sqlFilterMatr:
          " and  t1.id not in  ( select unit_id from location_limit_matr  where location_id ='" +
          this.locationInitData.id +
          "' ) ",
      }
      this.$refs.dvLimitMatr.setEditUserParam('packageUnit', userParam)
    },
    //绑定或者解绑
    resetFormDate() {
      this.$set(this.form, 'scanLocationCode', '')
      this.$set(this.form, 'scanUniqueCode', '')
      this.$set(this.form, 'scanUniqueCode2', '')
    },
    bindOrUnbind(formName, isWin, drawerName) {
      this.$refs[formName].validate().then((result) => {
        console.log('result', result)
        if (result && result == true) {
          let url = `/location/limit_matr/bindOrUnbind?uniqueCode=${this.form.scanUniqueCode}&locationCode=${this.form.scanLocationCode}`
          if (isWin == true) {
            this.form.scanUniqueCode2 = this.strings.trimrl(this.form.scanUniqueCode2)
            url = `/location/limit_matr/bindOrUnbind?uniqueCode=${this.form.scanUniqueCode2}&locationCode=${this.locationInitData.code}`
          } else {
            this.form.scanLocationCode = this.strings.trimrl(this.form.scanLocationCode)
          }
          console.log('url', url)
          this.$ajax.get(url).then((resp) => {
            if (resp.code == 0) {
              this.utilMessage.success(resp.msg)
              if (isWin == true) {
                this.form.scanUniqueCode2 = ''
                this.$refs.scanUniqueCode2.focus()
                this.$refs.dvLimitMatr.fetchData()
              } else {
                this.form.scanUniqueCode = ''
              }
            }
            this.resetFormDate()
            this.$refs[drawerName].hide()
          })
        }
      })
    },
    handleDrawerCancel() {
      this.resetFormDate()
    },

    //按钮操作前
    beforeButtonClick({ btn, call }) {
      if (btn.code == 'vb-add') { //添加前
        if (!this.selectedTreeNode || this.selectedTreeNode.id == 0) {
          this.utilMessage.warning('左侧库位树请选择非跟节点进行添加操作')
          call(false)
        }
      }
    }
  },
  created() {},
  components: {
    MatrSelect,
    treeLocation,
  },
}
</script>

<style lang="scss" scoped>
.container {
  height: 100%;
  background-color: #fff;
}

.tree-container {
  padding: 10px;
  margin-right: 20px;
  border: solid 1px #dcdfe6;
  height: 100%;
}

.tree-filter {
  margin: 10px;
  width: 80%;
}
</style>
